from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt

from square.models import OrdinaryUser
from django.views.generic import TemplateView, ListView, DetailView
from square.models import SparkCard
from django.contrib.auth import login
import requests

# # 登陆界面
def Login(request):
    return render(request, "sparkIndex/login.html")


def logout(request):
    rep = redirect("/index/")
    request.session.delete()
    # 登出，则删除掉session中的某条数据
    if 'is_login' in request.session:
        del request.session['is_login']
    return rep


def check_login(func):
    def inner(request, *args, **kwargs):
        next_url = request.get_full_path()
        # 获取session判断用户是否已登录
        if request.session.get('is_login'):
            # 已经登录的用户...
            return func(request, *args, **kwargs)
        else:
            # 没有登录的用户，跳转刚到登录页面
            return redirect("login")

    return inner


@check_login
def redirect_to_index(request):
    return redirect('index')


class LoginView(TemplateView):

    def get(self, request, *args, **kwargs):
        return render(request, 'sparkIndex/register.html')


    @csrf_exempt
    def post(self, request, *args, **kwargs):
        request.session.set_test_cookie()
        if request.session.test_cookie_worked():
            user_name = request.POST.get('user_name')
            password = request.POST.get("password")
            user = OrdinaryUser()
            context = user.test_user_and_password(user_name, password)  # 如果正确
            if context == True:  # 如果最终结果是True，表示数据都正确
                user = OrdinaryUser.objects.get(user_name=user_name)  # 获取用户id
                user_id = user.id
                request.session['user_id'] = user_id
                request.session['user_name'] = user_name
                # request.session['password'] = password
                # request.session['user'] = user  # 直接将该实例赋值给user key
                request.session['is_login'] = True
                print("id", request.session['user_id'])
                response = redirect('index')
            else:
                response = render(request, 'sparkIndex/login.html', context=context)
            return response
        else:
            return HttpResponse("Please enable cookies and try again.")


def register(request):
    """
        1、检查用户是否存在
        2、查看密码是否相等
    """
    user = OrdinaryUser()
    user_name = request.POST.get('user_name')
    if user.get_user_status(user_name) :   # 如果用户名存在
        return render(request, 'sparkIndex/register.html', {"username": -1})  # 返回用户名错误

    psw1 = request.POST.get('password1')
    psw2 = request.POST.get('password2')
    if psw1 != psw2:
        return render(request, 'sparkIndex/register.html', {"password": -1})  # 返回密码不相等的代码

    email = request.POST.get('email')
    """经历以上后，如果都正确，则新建一个用户"""
    user.create_new_user(user_name, psw1, email)
    return render(request, 'sparkIndex/login.html', {"register_true": 1})



# 广场界面的所有信息
class SparkListView(ListView):

    model = SparkCard
    paginate_by = 7     # 2页一个
    template_name = 'sparkIndex/index.html'  # 指定要渲染的模板文件
    context_object_name = 'spark_list'  # 如果没有指定，则默认为modelName_list (modelNmae为模型名字，且都为小写

    def get_queryset(self):
        return SparkCard.objects.order_by('-created_time')  # 时间

# 详细信息界面
class SparkDetail(DetailView): # 继承 detailview
    model = SparkCard
    template_name = 'sparkIndex/sparkdetail.html'
    context_object_name = 'one_spark'
    pk_url_kwarg = 'spark_id'  # 将查询的pk设置为spark_id


# 新增一个灵感
@check_login
def add_new_spark(request):  # 在发布之前需要登录，才可以发布
    data = request.POST
    # print(request.POST.get('spark_title'), request.POST.get('spark_content'), request.session.get('user_name'))
    print(data)
    title = data.get('spark_title')
    content = data.get('spark_content')
    user_id = request.POST.get('user_id')
    print("title", title, "content:", content, "user_id", user_id)
    user = OrdinaryUser.objects.get(pk=user_id)  # 获取user的对象
    new_spark = SparkCard()  # 新建一个新的spark
    new_spark.title = title
    new_spark.spark_content = content
    new_spark.owner = user
    new_spark.save()
    return redirect('index')


# @check_login
# def vote(request):  # 投票的视图函数



